#How Do Observers Assess Resolve?
#September 26, 2018
#BJPS Replication 1.R

#This file loads the data, cleans it, and generates the necessary variables and dataframe. Load this file first, or just load the saved objects at the top of BJPS Replication 2.R

# All of the following analyses were carried out using R version 3.4.3. GUI 1.70 (El Capitan build) on a 2.0 GHz quad-core Intel Core i7 Macbook Pro running Mac OS 10.13.4. 

#Libraries to load
library(foreign)
library(psych)
library(here) #Avoids needing to setwd()

data <- get(load("Resolve Conjoint Raw 070718.RData"))

#First, to make things more manageable, create a version of the dataset with just respondent ID and treatments
dat <- data[,c(1,4:129)]

#Now create new version of the dataset, with N*16 rows, a variable for the round (1-8), the country (A or B), and the treatment for that particular country
dat2 <- data.frame(ID=rep(dat$V1, each=16), Round=c(rep(rep(1:8, each=2),nrow(dat))), Country=rep(c("A","B"), nrow(dat)*8), RegimeType=NA, Capabilities=NA, Stakes=NA,NewLeader=NA, milService=NA, maleLeader=NA, actor=NA, prevBehavior=NA, curBehavior=NA)

#Go through the dataset in blocks by participant ID
for (i in unique(dat$V1)){
	block <- which(dat2$ID==i) #Find block in new dataset pertaining to participant i (16 consecutive rows, 2 per round)
	loc <- which(dat$V1==i) #Find location in old dataset pertaining to participant i

	#Now, for that participant, figure out the order the feature rows appeared in the table
	ordering <- dat[loc, c(2,4,6,8,10,12,14)] #Just extracts ordering from country A, since it should be the same for both

	#Now calculate column ordering - this will be constant across all rounds a subject plays
	RegimeTypeO <- which(ordering=="Government type")
	CapabilitiesO <- which(ordering=="Military capabilities")
	StakesO <- which(ordering=="Interests in the dispute")
	NewLeaderO <- milServiceO <- maleLeaderO <- which(ordering=="Leader background")
	actorO <- which(ordering=="Foreign relations")
	prevBehaviorO <- which(ordering=="Previous behavior in international disputes")
	curBehaviorO <- which(ordering=="Current behavior")
	
	#Now go through variables, first by country then by round
	for (j in c("A","B")){
		for (k in 1:8){
			dat2$RegimeType[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,RegimeTypeO,sep="."))]
			dat2$Capabilities[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,CapabilitiesO,sep="."))]
			dat2$Stakes[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,StakesO,sep="."))]
			dat2$NewLeader[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,NewLeaderO,sep="."))]
			dat2$milService[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,milServiceO,sep="."))]
			dat2$maleLeader[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,maleLeaderO,sep="."))]
			dat2$actor[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,actorO,sep="."))]
			dat2$prevBehavior[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,prevBehaviorO,sep="."))]
			dat2$curBehavior[block][(2*k)-ifelse(j=="A",1,0)] <- dat[loc,which(colnames(dat)==paste("F",k,j,curBehaviorO,sep="."))]					
		}	
	}
}
#Takes a couple of minutes

#Now, convert verbose treatments into specific levels
dat2$RegimeType[grep("in between", dat2$RegimeType)] <- "Mixed" #This needs to come before the other replacements, for obvious reasons
dat2$RegimeType[grep("democracy", dat2$RegimeType)] <- "Democracy"
dat2$RegimeType[grep("dictatorship", dat2$RegimeType)] <- "Dictatorship"

dat2$Capabilities[grep("not have", dat2$Capabilities)] <- "Low"
dat2$Capabilities[grep("has a", dat2$Capabilities)] <- "High"

dat2$Stakes[grep("high", dat2$Stakes)] <- "High"
dat2$Stakes[grep("low", dat2$Stakes)] <- "Low"

dat2$NewLeader[grep("recently", dat2$NewLeader)] <- "New"
dat2$NewLeader[grep("many years", dat2$NewLeader)] <- "Experienced"

dat2$milService[grep("not have", dat2$milService)] <- "None"
dat2$milService[grep("briefly", dat2$milService)] <- "Some"
dat2$milService[grep("long", dat2$milService)] <- "High"

dat2$maleLeader[grep("she", dat2$maleLeader)] <- "Female"
dat2$maleLeader[grep("he ", dat2$maleLeader)] <- "Male"

dat2$actor[grep("adversary", dat2$actor)] <- "Adversary" 
dat2$actor[grep("ally", dat2$actor)] <- "Ally"
dat2$actor[grep("United States", dat2$actor)] <- "USA" #This needs to come last for obvious reasons

dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an adversary of the United States, and stood firm throughout the crisis.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Initiator, stood firm against adversary, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an adversary of the United States, and stood firm throughout the crisis.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Initiator, stood firm against adversary, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an adversary of the United States, but ultimately backed down.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Initiator, backed down against adversary, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an adversary of the United States, but ultimately backed down. At the time, the country was led by a different leader than the one in the current dispute.")] <- "Initiator, backed down against adversary, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an ally of the United States, and stood firm throughout the crisis.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Initiator, stood firm against ally, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an ally of the United States, and stood firm throughout the crisis.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Initiator, stood firm against ally, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an ally of the United States, but ultimately backed down.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Initiator, backed down against ally, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it initiated the crisis by issuing a public threat to use force against an ally of the United States, but ultimately backed down.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Initiator, backed down against ally, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an adversary of the United States, who issued a public threat to use force; the country ultimately stood firm against the adversary.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Target, stood firm against adversary, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an adversary of the United States, who issued a public threat to use force; the country ultimately stood firm against the adversary.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Target, stood firm against adversary, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an adversary of the United States, who issued a public threat to use force; the country ultimately backed down against the adversary.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Target, backed down against adversary, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an adversary of the United States, who issued a public threat to use force; the country ultimately backed down against the adversary.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Target, backed down against adversary, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an ally of the United States, who issued a public threat to use force; the country ultimately stood firm against the ally.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Target, stood firm against ally, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an ally of the United States, who issued a public threat to use force; the country ultimately stood firm against the ally.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Target, stood firm against ally, same leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an ally of the United States, who issued a public threat to use force; the country ultimately backed down against the ally.  / At the time, the country was led by a different leader than the one in the current dispute.")] <- "Target, backed down against ally, different leader"
dat2$prevBehavior[which(dat2$prevBehavior=="The last time this country was involved in an international dispute, it was challenged by an ally of the United States, who issued a public threat to use force; the country ultimately backed down against the ally.  / At the time, the country was led by the same leader as the one in the current dispute.")] <- "Target, backed down against ally, same leader"

dat2$curBehavior[grep("public threat", dat2$curBehavior)] <- "Public threat"
dat2$curBehavior[grep("mobilized troops", dat2$curBehavior)] <- "Mobilized troops"
dat2$curBehavior[grep("yet to make", dat2$curBehavior)] <- "Nothing"

#Now merge back in DVs and response times
dat2$Chosen <- NA
dat2$Rating <- NA
dat2$responseTime <- NA

#Go through each observation
for (i in unique(data$V1)){
	block <- which(dat2$ID==i) #Find block in new dataset pertaining to participant i (16 consecutive rows, 2 per round)
	loc <- which(data$V1==i) #Find location in old dataset pertaining to participant i
	#Go through round by round
	for (k in 1:8){
		#Choice-based task
		if(data[loc,which(colnames(data)==paste("c",k,"c", sep=""))]=="1"){
			dat2$Chosen[block][(2*k)-1] <- 1
			dat2$Chosen[block][(2*k)] <- 0
		} else if(data[loc,which(colnames(data)==paste("c",k,"c", sep=""))]=="2"){
			dat2$Chosen[block][(2*k)-1] <- 0
			dat2$Chosen[block][(2*k)] <- 1			
			}
		#Ratings-based task
		dat2$Rating[block][(2*k)-1] <- data[loc, which(colnames(data)==paste("c",k,"ra_1", sep=""))]
		dat2$Rating[block][(2*k)] <- data[loc, which(colnames(data)==paste("c",k,"rb_1", sep=""))]
		
		#Response latencies
		dat2$responseTime[block][((2*k)-1):(2*k)] <- data[loc, which(colnames(data)==paste("t",k,"_3",sep=""))]			
	}
}

dat2$ID_numeric <- as.numeric(dat2$ID) #Generate numeric ID variable

#Specify levels of factors
dat2$RegimeType <- as.factor(dat2$RegimeType)
dat2$RegimeType <- relevel(dat2$RegimeType, ref="Dictatorship")
dat2$Capabilities <- as.factor(dat2$Capabilities)
dat2$Capabilities <- relevel(dat2$Capabilities, ref="Low")
dat2$Stakes <- as.factor(dat2$Stakes)
dat2$Stakes <- relevel(dat2$Stakes, ref="Low")
dat2$NewLeader <- as.factor(dat2$NewLeader)
dat2$NewLeader <- relevel(dat2$NewLeader, ref="Experienced")
dat2$milService <- as.factor(dat2$milService)
dat2$milService <- relevel(dat2$milService, ref="None")
dat2$maleLeader <- as.factor(dat2$maleLeader)
dat2$maleLeader <- relevel(dat2$maleLeader, ref="Female")
dat2$actor <- as.factor(dat2$actor)
dat2$actor <- relevel(dat2$actor, ref="Ally")
dat2$prevBehavior <- as.factor(dat2$prevBehavior)
dat2$prevBehavior <- relevel(dat2$prevBehavior, ref="Target, stood firm against ally, different leader")
dat2$curBehavior <- as.factor(dat2$curBehavior)
dat2$curBehavior <- relevel(dat2$curBehavior, ref="Nothing")

######## Disaggregating previous behavior
dat2$prevOpponent <- NA
dat2$prevOpponent[grep("ally", dat2$prevBehavior)] <- "Ally"
dat2$prevOpponent[grep("adversary", dat2$prevBehavior)] <- "Adversary"
dat2$prevOpponent <- as.factor(dat2$prevOpponent)
dat2$prevOpponent <- relevel(dat2$prevOpponent, ref="Ally")

dat2$prevRole <- NA
dat2$prevRole[grep("Target", dat2$prevBehavior)] <- "Target"
dat2$prevRole[grep("Initiator", dat2$prevBehavior)] <- "Initiator"
dat2$prevRole <- as.factor(dat2$prevRole)
dat2$prevRole <- relevel(dat2$prevRole, ref="Target")

dat2$prevAct <- NA
dat2$prevAct[grep("stood firm", dat2$prevBehavior)] <- "Stood firm"
dat2$prevAct[grep("backed down", dat2$prevBehavior)] <- "Backed down"
dat2$prevAct <- as.factor(dat2$prevAct)
dat2$prevAct <- relevel(dat2$prevAct, ref="Stood firm")

dat2$prevLdr <- NA
dat2$prevLdr[grep("same leader", dat2$prevBehavior)] <- "Same leader"
dat2$prevLdr[grep("different leader", dat2$prevBehavior)] <- "Different leader"
dat2$prevLdr <- as.factor(dat2$prevLdr)
dat2$prevLdr <- relevel(dat2$prevLdr, ref="Different leader")

dat2$prevActLdr <- NA
dat2$prevActLdr[which(dat2$prevLdr=="Same leader" & dat2$prevAct== "Stood firm")] <- "Same leader, stood firm"
dat2$prevActLdr[which(dat2$prevLdr=="Different leader" & dat2$prevAct== "Stood firm")] <- "Different leader, stood firm"
dat2$prevActLdr[which(dat2$prevLdr=="Different leader" & dat2$prevAct== "Backed down")] <- "Different leader, backed down"
dat2$prevActLdr[which(dat2$prevLdr=="Same leader" & dat2$prevAct== "Backed down")] <- "Same leader, backed down"
dat2$prevActLdr <- as.factor(dat2$prevActLdr)
dat2$prevActLdr <- relevel(dat2$prevActLdr, ref="Different leader, stood firm")

##### More complex hypotheses

## Current calculus hypothesis

dat2$backCapInt <- NA
dat2$backCapInt[which(dat2$prevAct=="Backed down" & dat2$Capabilities=="High" & dat2$"Stakes"=="High")] <- "Backed down, high capabilities, high stakes"
dat2$backCapInt[which(dat2$prevAct=="Backed down" & dat2$Capabilities=="Low" & dat2$"Stakes"=="High")] <- "Backed down, low capabilities, high stakes"
dat2$backCapInt[which(dat2$prevAct=="Backed down" & dat2$Capabilities=="High" & dat2$"Stakes"=="Low")] <- "Backed down, high capabilities, low stakes"
dat2$backCapInt[which(dat2$prevAct=="Backed down" & dat2$Capabilities=="Low" & dat2$"Stakes"=="Low")] <- "Backed down, low capabilities, low stakes"
dat2$backCapInt[which(dat2$prevAct=="Stood firm" & dat2$Capabilities=="High" & dat2$"Stakes"=="High")] <- "Stood firm, high capabilities, high stakes"
dat2$backCapInt[which(dat2$prevAct=="Stood firm" & dat2$Capabilities=="Low" & dat2$"Stakes"=="High")] <- "Stood firm, low capabilities, high stakes"
dat2$backCapInt[which(dat2$prevAct=="Stood firm" & dat2$Capabilities=="High" & dat2$"Stakes"=="Low")] <- "Stood firm, high capabilities, low stakes"
dat2$backCapInt[which(dat2$prevAct=="Stood firm" & dat2$Capabilities=="Low" & dat2$"Stakes"=="Low")] <- "Stood firm, low capabilities, low stakes"

#### Attribution theory hypothesis
dat2$desirable <- NA
dat2$desirable[which(dat2$actor=="Ally" & dat2$prevAct=="Backed down")] <- "Ally, backed down"
dat2$desirable[which(dat2$actor=="Adversary" & dat2$prevAct=="Backed down")] <- "Adversary, backed down"
dat2$desirable[which(dat2$actor=="Ally" & dat2$prevAct=="Stood firm")] <- "Ally, stood firm"
dat2$desirable[which(dat2$actor=="Adversary" & dat2$prevAct=="Stood firm")] <- "Adversary, stood firm"
dat2$desirable <- as.factor(dat2$desirable)
dat2$desirable <- relevel(dat2$desirable, ref="Ally, backed down")

dat2$desirable2 <- NA
dat2$desirable2[which(dat2$actor=="Ally" & dat2$prevAct=="Backed down" & dat2$prevOpponent == "Ally")] <- "Ally, backed down against ally"
dat2$desirable2[which(dat2$actor=="Adversary" & dat2$prevAct=="Backed down" & dat2$prevOpponent == "Ally")] <- "Adversary, backed down against ally"
dat2$desirable2[which(dat2$actor=="Ally" & dat2$prevAct=="Stood firm" & dat2$prevOpponent == "Ally")] <- "Ally, stood firm against ally"
dat2$desirable2[which(dat2$actor=="Adversary" & dat2$prevAct=="Stood firm" & dat2$prevOpponent == "Ally")] <- "Adversary, stood firm against ally"
dat2$desirable2[which(dat2$actor=="Ally" & dat2$prevAct=="Backed down"&  dat2$prevOpponent == "Adversary")] <- "Ally, backed down against adversary"
dat2$desirable2[which(dat2$actor=="Adversary" & dat2$prevAct=="Backed down" & dat2$prevOpponent == "Adversary")] <- "Adversary, backed down against adversary"
dat2$desirable2[which(dat2$actor=="Ally" & dat2$prevAct=="Stood firm" & dat2$prevOpponent == "Adversary")] <- "Ally, stood firm against adversary"
dat2$desirable2[which(dat2$actor=="Adversary" & dat2$prevAct=="Stood firm" & dat2$prevOpponent == "Adversary")] <- "Adversary, stood firm against adversary"
dat2$desirable2 <- as.factor(dat2$desirable2)
dat2$desirable2 <- relevel(dat2$desirable2, ref="Ally, backed down against adversary")

#### Democratic credibility theory

dat2$audCost <- NA
dat2$audCost[which(dat2$RegimeType=="Dictatorship" & dat2$curBehavior=="Public threat")] <- "Dictatorship, public threat"
dat2$audCost[which(dat2$RegimeType=="Mixed" & dat2$curBehavior=="Public threat")] <- "Mixed, public threat"
dat2$audCost[which(dat2$RegimeType=="Democracy" & dat2$curBehavior=="Public threat")] <- "Democracy, public threat"
dat2$audCost[which(dat2$RegimeType=="Dictatorship" & dat2$curBehavior=="Nothing")] <- "Dictatorship, nothing"
dat2$audCost[which(dat2$RegimeType=="Mixed" & dat2$curBehavior=="Nothing")] <- "Mixed, nothing"
dat2$audCost[which(dat2$RegimeType=="Democracy" & dat2$curBehavior=="Nothing")] <- "Democracy, nothing"
dat2$audCost <- as.factor(dat2$audCost)
dat2$audCost <- relevel(dat2$audCost, ref="Dictatorship, nothing")

###Create version of dataframe without US observations (how *observers* assess resolve)
dat3 <- subset(dat2, dat2$actor!="USA")
#But now we need to get rid of the orphans left behind from pairs where the US was one of the countries
for (i in unique(dat3$ID_numeric)){
	block <- which(dat3$ID_numeric==i) #Find block in new dataset pertaining to participant i (should be 16 consecutive rows, 2 per round)
	if (length(block)<16){ # If some are missing:
		j <- which(table(dat3$Round[block])==1)
		dat3 <- dat3[-block[match(j, dat3$Round[block])],]
	}
}

#Save versions of data
save(dat2, file="Resolve Conjoint Cleaned 070718.RData")
save(dat3, file="Resolve Conjoint Cleaned No US 070718.RData")

####### Generate weights

##### Now, generate demographic variables needed to generate weights
dat_id <- data.frame(ID=as.factor(data$V1)) #Uses original dataframe

#Functions to recode our variables
recode2 <- function(variable, reverse=FALSE, maxVal, minVal, binarize=FALSE, x=NA, x2){
	if (is.factor(variable)){variable <- as.numeric(variable)}
	if (is.character(variable)){variable <- as.numeric(variable)}	
	if (missing(maxVal)){maxVal <- max(variable, na.rm=TRUE)}
	if (missing(minVal)){minVal <- min(variable, na.rm=TRUE)}
	variable[variable > maxVal] <- NA
	variable[variable < minVal] <- NA
	if (reverse){
		temp <- variable
		for (j in 1:maxVal){
			temp[which(variable==j)] <- maxVal-j+1
		}
		return(as.numeric(temp))
	}
	if (binarize){
		if (is.na(x)){stop("Specify the value to dichotomize on")}
		temp <- variable
		if (missing(x2)){
			i <- which(variable == x)
			k <- which(variable < x | variable > x)
		}
		else{
			i <- which(variable >= x & variable <= x2)
			k <- which(variable < x | variable > x2)
		}
		temp[i] <- 1
		temp[k] <- 0
		return(temp)
	}
	return(as.numeric(variable))
}


#Rescales variable to range between 0-1 (used for scales)
rescale <- function(x){
	return((x-min(x,na.rm=TRUE))/(max(x-min(x,na.rm=TRUE),na.rm=TRUE)))
}

#Gender
dat_id$male <- recode2(as.numeric(data$Q58), binarize=TRUE, x=1)

#Age
dat_id$age <- 2015-as.numeric(data$Q60)

#Create age dummies for easier weighting
dat_id$age1 <- recode2(dat_id$age, binarize=TRUE, x=18, x2=24)
dat_id$age2 <- recode2(dat_id$age, binarize=TRUE, x=25, x2=44)
dat_id$age3 <- recode2(dat_id$age, binarize=TRUE, x=45, x2=64)
dat_id$age4 <- recode2(dat_id$age, binarize=TRUE, x=65, x2=80)

#Education
dat_id$educ <- recode2(data$Q62)
dat_id$educ1 <- recode2(dat_id$educ, binarize=TRUE, x=1, x2=2) #HS or less
dat_id$educ2 <- recode2(dat_id$educ, binarize=TRUE, x=3) #Some college
dat_id$educ3 <- recode2(dat_id$educ, binarize=TRUE, x=4, x2=5) #College/University
dat_id$educ4 <- recode2(dat_id$educ, binarize=TRUE, x=6, x2=8) #Post-grad

#Find missing gender observation, temporarily drop it for weight generation
j <- which(is.na(dat_id$male))
k <- dat_id[j,]
dat_id <- dat_id[-j,]

#Export dataset to Stata
write.dta(dat_id, file="Resolve Weights 070718.dta")

## Now, run the following code in Stata (note that you'll need to set the file path)
#use "/Users/jkertzer/Dropbox/Shared work with Josh and Keren-Reputation/Conjoint Paper/BJPS submission Sept 2017/Revisions/BJPS Replication/BJPS Replication Materials/Resolve Weights 070718.dta"
#ebalance male age2 age3 age4 educ2 educ3 educ4, manualtargets(0.492 0.342 0.341 0.189 0.1942 0.2823 0.1038)
#recode _webal (5/100=5), gen(eWeight)
#rename _webal webal
#saveold "/Users/jkertzer/Dropbox/Shared work with Josh and Keren-Reputation/Conjoint Paper/BJPS submission Sept 2017/Revisions/BJPS Replication/BJPS Replication Materials/Resolve Weights 070718.dta", replace

#Now, re-load data
dat_id <- read.dta(file="Resolve Weights 070718.dta")
#Add in missing row
k$eWeight <- k$webal <- NA
dat_id <- rbind(dat_id,k) #Add in missing row

#Generate numeric ID for merging purposes
dat_id$ID_numeric <- as.numeric(dat_id$ID) #Generate numeric ID variable

#Now, merge weights in with the main dataset
dat_id2 <- dat_id[,c(15,14)]
dat3 <- merge(dat3, dat_id2, by="ID_numeric")
save(dat3, file="Resolve Conjoint Cleaned No US 070718.RData")

#Now, create remaining demographic and individual difference variables

#MI
mi1r <- recode2(data$Q40, reverse=TRUE)
mi2r <- recode2(data$Q42)
mi3r <- recode2(data$Q44, reverse=TRUE)
mi4r <- recode2(data$Q46, reverse=TRUE)

#CI
ci1r <- recode2(data$Q48, reverse=TRUE)
ci2r <- recode2(data$Q50, reverse=TRUE)

#Isolationism
iso1 <- recode2(data$Q52)
iso2 <- recode2(data$Q54, reverse=TRUE)

alpha(cbind(mi1r, mi2r, mi3r, mi4r)) #a=0.78 for MI
dat_id$mi1 <- rescale(mi1r + mi2r + mi3r + mi4r)

alpha(cbind(ci1r, ci2r))  #a=0.64 for CI
dat_id$ci1 <- rescale(ci1r + ci2r)

alpha(cbind(iso1, iso2)) #a=0.78 for Isolationism
dat_id$iso1 <- rescale(iso1 + iso2)

#Mean-split mi
dat_id$mi2 <- rep(NA, nrow(dat_id))
dat_id$mi2[which(dat_id$mi1 < mean(dat_id$mi1, na.rm=TRUE))] <- 0
dat_id$mi2[which(dat_id$mi1 >= mean(dat_id$mi1, na.rm=TRUE))] <- 1

#Party ID (scaled towards Republican)
dat_id$partyID <- rescale(recode2(data$Q64, reverse=TRUE))
dat_id$Dems <- rep(NA, nrow(dat_id))
dat_id$Reps <- rep(NA, nrow(dat_id))
dat_id$Dems[which(dat_id$partyID <0.34)] <- 1
dat_id$Dems[which(dat_id$partyID > 0.34)] <- 0
dat_id$Reps[which(dat_id$partyID > 0.66)] <- 1
dat_id$Reps[which(dat_id$partyID < 0.66)] <- 0

#Ideology (scaled toward conservative)
dat_id$ideology <- rescale(recode2(data$Q66, reverse=TRUE))

#Attention & interest
dat_id$interestFP <- rescale(recode2(data$Q52, reverse=TRUE)) #Ranges from 0-1
dat_id$interestGov <- rescale(recode2(data$Q53, reverse=TRUE)) #Ranges from 0-1

cor(dat_id$interestFP, dat_id$interestGov, use="complete.obs") #r=0.067 - they're pretty independent, keep separate

#Intl trust
dat_id$intTrust1 <- rescale(recode2(data$Q54, binarize=TRUE, x=1))

#Save demographic dataframe (we need a standalone version for sample characteristic calculations, etc.)
save(dat_id, file="Resolve Demographics 070718.RData")